#!/usr/bin/env python3

from literatureTool.config.config import config 
import hashlib
import sys
import time
import subprocess
import os
from literatureTool.literature import literature


def run():
    functions = {}
    functions['scan'] = scan
    functions['addkeys'] = addkeys
    functions['addauthors'] = addauthors
    functions['querykeys'] = querykeys
    functions['infos'] = infos
    functions['list'] = list_literatures
    functions['read'] = read
    functions['unread'] = unread
    functions['open'] = literature_open
    functions['md5'] = files_md5
    if len(sys.argv)>1 and sys.argv[1] in functions:
        functions[sys.argv[1]]()
    else:
        help_msg()


def help_msg():
    print("python3 literatureTool.py scan")
    print("python3 literatureTool.py addkeys [key] [sign]")
    print("python3 literatureTool.py addauthors [author] [sign]")
    print("python3 literatureTool.py querykeys [key]")
    print("python3 literatureTool.py open [sign]")
    print("python3 literatureTool.py list [read]")
    print("python3 literatureTool.py list [unread]")
    print("python3 literatureTool.py read [sign]")
    print("python3 literatureTool.py unread [sign]")
    print("python3 literatureTool.py infos [sign]")
    print("python3 literatureTool.py md5 [filePath]")

def files_md5():
    if len(sys.argv[2:]) >= 1:
        pt = [os.path.abspath(os.path.expanduser(i)) for i in sys.argv[2:]]
        files = (open(file_path, "rb") for file_path in pt)
        md5 = hashlib.md5()
        for file in files:
            md5.update(file.read())
            file.close()
            print(md5.hexdigest())
    else:
        help_msg()


def scan():
    a = config()
    cmd = "find " + a.scan_directory + " -type f -name \"*.pdf\""
    result = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    for pdf in result.stdout.read().decode("utf-8").split("\n"):
        if os.path.exists(pdf):
            l = literature.literature(pdf)
            if not os.path.exists(l.literature_dataPath):
                l.saveLiteratureData()
    for data_file_path in literature_dataPaths():
        l = literature.loadLiteratureFromDataFile(data_file_path)
        if not l:
            os.remove(data_file_path)


def addkey(source, dest):
    dests = match(dest, literature_dataPaths())
    if len(dests) != 1:
        print("you should input right dest.")
        print("literatureTool.py addkey [source] [dest]")
    else:
        l = literature.loadLiteratureFromDataFile(dests[0])
        l.addKey(source)
        l.saveLiteratureData()


def addauthor(author, dest):
    dests = match(dest,literature_dataPaths())
    if len(dests) != 1:
        print("you should input right dest.")
        print("literatureTool.py addauthor [source] [dest]")
    else:
        l = literature.loadLiteratureFromDataFile(dests[0])
        l.addAuthor(author)
        l.saveLiteratureData()


def match(str, list):
    ret = []
    for i in list:
        if str in i:
            ret.append(i)
    return ret

def querykey(listStr):
    if (len(listStr)) == 0:
        print("you should input some keys.")
    else:
        ret = PreLiteratures = [literature.loadLiteratureFromDataFile(data_file_path) for data_file_path in literature_dataPaths()]
        for key in listStr:
            PreLiteratures = ret
            ret = []
            for l in PreLiteratures:
                if key in l.literature_keys:
                    ret.append(l)
        return ret

def literature_dataPaths():
    a = config()
    data_files = os.listdir(a.literatures_DB_directory)
    return [os.path.join(a.literatures_DB_directory, data_file) for data_file in data_files]


def infos():
    info(sys.argv[2:])


def info(listLiterations):
    for sign in listLiterations:
        data_paths = match(sign, literature_dataPaths())
        if len(data_paths) != 1:
            print("you should input more rightly sign of ", sign)
            break
        l = literature.loadLiteratureFromDataFile(data_paths[0])
        l.literation_info()


def literature_open():
    if len(sys.argv[2:]) == 1:
        data_paths = match(sys.argv[2], literature_dataPaths())
        if len(data_paths) == 1:
            l = literature.loadLiteratureFromDataFile(data_paths[0])
            # open literature.
            os.system("wpspdf " + l.literature_filePath + "&")
            l.addReadHistory(time.asctime(time.localtime(time.time())))
            l.saveLiteratureData()
        else:
            print("you should input more rightly sign of ", sys.argv[2])


def list_literatures():
    list_functions = {}
    list_functions['all'] = lambda l:True if l else False
    list_functions['read'] = lambda l:l.literature_isread if l else False
    list_functions['unread'] = lambda l: not l.literature_isread if l else False
    if len(sys.argv) and sys.argv[2] in list_functions:
        literatures = [literature.loadLiteratureFromDataFile(data_path) for data_path in literature_dataPaths()]
        ls = list(filter(lambda l:l,list(filter(list_functions[sys.argv[2]], literatures))))
        for i,l in zip(range(1, len(ls)+1), ls):
            print(i,"\t", l.literature_sign)
    else:
        help_msg()


def read():
    if len(sys.argv) >=3:
        data_paths = []
        for sign in sys.argv[2:]:
            t = match(sign, literature_dataPaths())
            if len(t) == 1:
                data_paths.append(t[0])
            else:
                print("you should input more rightly sign of ",sign)
        ls = [literature.loadLiteratureFromDataFile(data_path) for data_path in data_paths]
        for  l in ls:
            if not l.literature_isread:
                l.addReadHistory(time.asctime(time.localtime(time.time())))
                l.saveLiteratureData()


def unread():
    if len(sys.argv) >= 3:
        data_paths = []
        for sign in sys.argv[2:]:
            t = match(sign, literature_dataPaths())
            if len(t) == 1:
                data_paths.append(t[0])
            else:
                print("you should input more rightly sign of ",sign)
        ls = [literature.loadLiteratureFromDataFile(data_path) for data_path in data_paths]
        for l in ls:
            if l.literature_isread:
                l.literature_history = []
                l.literature_isread = 0
                l.saveLiteratureData()


def addkeys():
    if len(sys.argv) < 4:
        print("python3 literatureTool.py addkeys [key] [sign]")
        return
    for i in sys.argv[2:-1]:
        addkey(i, sys.argv[-1])


def addauthors():
    if len(sys.argv) < 4:
        print("python3 literatureTool.py addauthors [author] [sign]")
        return
    for i in sys.argv[2:-1]:
        addauthor(i, sys.argv[-1])


def querykeys():
    if len(sys.argv) < 3:
        print("python3 literatureTool.py querykeys [key]")
        return
    for l in querykey(sys.argv[2:]):
        print(l.literature_dataPath)


if __name__ == "__main__":
    run()

